package mysql

import (
	"database/sql"
	"fmt"
	"strings"
	"web_app/models"

	"github.com/jmoiron/sqlx"

	"go.uber.org/zap"
)

// InsertPostModel 插入帖子详情数据
func InsertPostModel(postModel *models.Post) (err error) {
	sqlStr := "insert into post(post_id,title,content,author_id,community_id,status,create_time) " +
		"values(:post_id,:title,:content,:author_id,:community_id,:status,:create_time) "
	if _, err := db.NamedExec(sqlStr, postModel); err != nil {
		zap.L().Error("InsertPostModel() failed", zap.Error(err))
	}
	return
}

// GetPostDetailByID 根据帖子id获取帖子详情
func GetPostDetailByID(id int64) (postDetail *models.ApiPostDetail, err error) {
	sqlStr := "select p.post_id, p.content, p.create_time, p.status, p.title, c.community_name, u.username " +
		"from post as p left join user u on p.author_id=u.user_id left join community c on p.community_id=c.community_id " +
		"where p.post_id=?"
	postDetail = new(models.ApiPostDetail)
	fmt.Print(sqlStr)
	err = db.Get(postDetail, sqlStr, id)
	zap.L().Error("GetPostDetailByID() failed", zap.Error(err))
	if err != nil {
		if err == sql.ErrNoRows {
			err = ErrInvalidID
		}
	}
	return
}

// GetPostList 获取帖子列表
func GetPostList(page *models.Page) (postList []*models.ApiPostDetail, err error) {
	sqlStr := "select p.post_id, p.content, p.create_time, p.status, p.title, c.community_name, u.username " +
		"from post as p left join user u on p.author_id=u.user_id left join community c on p.community_id=c.community_id " +
		"limit ?,?"
	postList = make([]*models.ApiPostDetail, 0)
	err = db.Select(&postList, sqlStr, page.PageCount*(page.PageSize-1), page.PageCount)
	if err != nil {
		zap.L().Error("GetPostList() failed", zap.Error(err))
		if err == sql.ErrNoRows {
			err = ErrInvalidID
		}
	}
	return
}

// GetPostListByIDs 根据ids获取postList
func GetPostListByIDs(ids []string) ([]*models.ApiPostDetail, error) {
	sqlStr := "select p.post_id, p.content, p.create_time, p.status, p.title, c.community_name, u.username " +
		"from post as p left join user u on p.author_id=u.user_id left join community c on p.community_id=c.community_id " +
		"where p.post_id in (?) " +
		"order by find_in_set(p.post_id,?)"
	postList := make([]*models.ApiPostDetail, 0)
	query, args, err := sqlx.In(sqlStr, ids, strings.Join(ids, ","))
	if err != nil {
		return nil, err
	}
	query = db.Rebind(query)
	err = db.Select(&postList, query, args...)
	if err != nil {
		return nil, err
	}
	return postList, nil
}
